using System;
using System.Linq;
using System.ComponentModel;
using System.Collections.Generic;
using Kingdee.BOS.Util;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;

namespace CZ.PAEZ.SaleManager.FormPlugIns
{
    [Description("费用报销单-携带部门负责人")]
    [HotUpdate]
    public class ExpReimbursementForm : AbstractBillPlugIn
    {
        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);
            string status = this.Model.GetValue("FDocumentStatus").ToString();
            if(status == "B" || status == "C") return;
            string key = e.Field.Key.ToString();
            if (key == "FExpenseDeptEntryID")
            {
                string userId = GetDepartmentManagerUserId(e.NewValue.ToString());
                if (userId == "0")
                {
                    this.View.ShowMessage("该部门未查询到对应的负责人！");
                    return;
                }
                this.Model.SetValue("F_PAEZ_Checker", userId, e.Row);
            }
        }

        public override void BeforeDoOperation(BeforeDoOperationEventArgs e)
        {
            switch(e.Operation.FormOperation.Operation.ToUpperInvariant())
            {
                case "SAVE":
                case "SUBMIT":
                    string status = this.Model.GetValue("FDocumentStatus").ToString();
                    if(status == "B" || status == "C") return;
                    Act_BDO_SetDepartmentManager();
                    break;
            }
            base.BeforeDoOperation(e);
        }

        private void Act_BDO_SetDepartmentManager()
        {
            var entity = this.Model.DataObject["ER_ExpenseReimbEntry"] as DynamicObjectCollection;
            for (var i = 0; i < entity.Count; i++)
            {
                string deptId = (entity[i]["ExpenseDeptEntryID"] as DynamicObject)?["Id"].ToString() ?? "0";
                string userId = GetDepartmentManagerUserId(deptId);
                this.Model.SetValue("F_PAEZ_Checker", userId, i);
            }
        }

        private string GetDepartmentManagerUserId(string deptId)
        {
            string sql = string.Format(@"select u.FUserId, u.FUSERACCOUNT from 
(select * from T_BD_DEPARTMENT where FDEPTID={0}) d
inner join T_BD_DEPARTMENT_L dl on dl.FDeptId=d.FDeptId
inner join T_ORG_POST p on p.FDEPTID=d.FDEPTID 
inner join T_ORG_HRPOST hp on hp.FPOSTID=p.FPOSTID and hp.FLEADERPOST=1
inner join T_BD_STAFF st on st.FPOSTID=p.FPOSTID and st.FFORBIDSTATUS='A'
inner join T_BD_STAFFPOSTINFO sti on sti.FSTAFFID=st.FSTAFFID --and sti.FIsFirstPost=1
inner join T_HR_EMPINFO e on e.FSTAFFNUMBER=st.FNUMBER
inner join V_bd_ContactObject c on c.FNumber=e.FNumber
inner join T_SEC_USER u on u.FLinkObject=c.FID", deptId);
            var item = DBUtils.ExecuteDynamicObject(this.Context, sql).FirstOrDefault();
            return item == null ? "0" : item["FUserId"].ToString();
        }
    }
}
